﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Vit.Common.Extensions;
using VitData = Vit.Web.DataAnnotations;

namespace Vit.CMS.Data
{
    [MetadataType(typeof(MvcControlInfoMetaData))]
    public class MvcControlInfo : Vit.Common.IStringSerializable
    {
        public MvcControlInfo(PageInfo pageInfo, object parent)
        {
            PageInfo = pageInfo;
            Parent = parent;
        }

        public string ID { get; set; }
        public string Url { get; set; }
        public string Content { get; set; }
        public int Indent { get; set; }

        public PageInfo PageInfo { get; private set; }
        public object Parent { get; private set; }

        #region IStringSerializable Members

        public string Serialize()
        {
            string html = string.Format(@"{0}<vit:MvcControl ID=""{1}"" runat=""server"" Url=""{2}""/>",
                "\t".Repeat(Indent), ID, Url);
            return html;
        }

        public void Deserialize(string value)
        {
            string ns = "vit:MvcControl";
            string pattern = string.Format(@"<{0}\s*(?<attributes>[^<>]*?)\s*((/>)|(>(?<content>(.|\r|\n)*?)</{0}>))", ns);
            Match match = null;
            RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline;

            string attibutes = "";
            match = Regex.Match(value, pattern, options);
            if (match.Success)
            {
                attibutes = match.Groups["attributes"].Value.Trim();
                this.Content = match.Groups["content"].Value.Trim();
            }

            pattern = @"ID\s*=\s*""(?<content>[^<>]+?)""";
            match = Regex.Match(attibutes, pattern, options);
            if (match.Success)
                this.ID = match.Groups["content"].Value.Trim();

            pattern = @"Url\s*=\s*""(?<content>[^<>]+?)""";
            match = Regex.Match(attibutes, pattern, options);
            if (match.Success)
                this.Url = match.Groups["content"].Value.Trim();
        }

        #endregion

        public class MvcControlInfoMetaData
        {
            [VitData.DisplayName("MvcControlInfo.ID")]
            public string ID { get; set; }
            [VitData.DisplayName("MvcControlInfo.Url")]
            [UIHint("MvcUrl")]
            public string Url { get; set; }
            [ScaffoldColumn(false)]
            public string Content { get; set; }
            [ScaffoldColumn(false)]
            public int Indent { get; set; }

            [ScaffoldColumn(false)]
            public PageInfo PageInfo { get; private set; }
            [ScaffoldColumn(false)]
            public object Parent { get; private set; }
        }
    }
}
